import { cloneDeep, findIndex } from 'lodash'
import { onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

const getFolder = (obj, list, _r) => {
  if (obj?.pid == 0) {
    // _r.push(obj)
  } else {
    let _index = findIndex(list, { id: obj.pid })
    if (_index >= 0) {
      //找到了
      _r.push(list[_index])
      getFolder(list[_index], list, _r)
    } else {
      //没有找到
      // _r.push(obj)
    }
  }
}

export default ({ key = 'id' }) => {
  let store = useStore()
  let route = useRoute()
  let router = useRouter()

  let addPath = (info) => {
    store.commit('spath', info)
  }
  let _w = watch(
    () => route.query[key],
    (newValue, preValue) => {
      //  store.commit('rePath', [])

      //  if (preValue == undefined) return
      if (newValue == preValue) return
      let _id = route.query[key]
      if (_id == undefined) {
        store.commit('breadcrumbPath', [])
        //当前是根目录
      } else {
        let current_obj_index = findIndex(store.state.singlePath, {
          id: parseInt(_id),
        })
        if (current_obj_index < 0) return

        let current_obj = store.state.singlePath[current_obj_index]

        // console.log(current_obj, store.state.singlePath, _id)
        let _r = [cloneDeep(current_obj)]

        getFolder(cloneDeep(current_obj), cloneDeep(store.state.singlePath), _r)
        store.commit('breadcrumbPath', _r)
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
  onUnmounted(() => {
    _w()
  })

  return [addPath]
}
